Home:ALL Converter>How to read/write float values from a binary file in python, if the file was created with C

How to read/write float values from a binary file in python, if the file was created with C

Ask Time:2021-10-28T18:02:25         Author:gabor aron

Json Formatter

I want to read/write C float values from a binary file if it was created in C?

The file was created like this:

#include <stdio.h>

int main() {
    const int NUMBEROFTESTELEMENTS = 10;
    /* Create the file */
    float x = 1.1;
    FILE *fh = fopen ("file.bin", "wb");
    if (fh != NULL) {
       for (int i = 0; i < NUMBEROFTESTELEMENTS; ++i)
       {
            x = 1.1*i;
            fwrite (&x,1, sizeof (x), fh);
            printf("%f\n", x);
       }
        fclose (fh);
    }

    return 0;
}

I found a method like this:

file=open("array.bin","rb")
number=list(file.read(3))
print (number)
file.close()

But this won't guarantee to me the read value was a C float.

Author:gabor aron,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69752048/how-to-read-write-float-values-from-a-binary-file-in-python-if-the-file-was-cre
mch :

import struct\nwith open("array.bin","rb") as file:\n numbers = struct.unpack('f'*10, file.read(4*10))\nprint (numbers)\n\nThis should do the job. numbers is a tuple of the 10 values.",
2021-10-28T10:45:36
yy